import os, sys
import gobject
from threading import Thread
from ftplib import FTP

class FTPConnection(gobject.GObject):
	
    __gsignals__ = {
                "dirchanged" :  (gobject.SIGNAL_RUN_LAST,
                gobject.TYPE_NONE,
                ()),
                "connected" :  (gobject.SIGNAL_RUN_LAST,
                gobject.TYPE_NONE,
                ())}
    
    _instance = None
    
    def __init__(self):
        gobject.GObject.__init__(self)
        self.ftp = FTP()
        self.status = False
        
    def connectTo(self, server, user, password):
        self.ftp.connect(server)
        self.ftp.login(user, password)
        self.status = True  
        self.emit("connected")
        
    def getWelcome(self):
    	return self.ftp.getwelcome()
    
    def quit(self):
    	self.ftp.quit()
          
    def closeConnection(self):
        self.ftp.quit()
        self.status = False
        
    def cwd(self, path):
        self.ftp.cwd(path)
        self.emit("dirchanged")
        
    def pwd(self):
        return self.ftp.pwd()
       
    def delete(self, file):
        self.ftp.delete(file)
        self.emit("dirchanged")
        
    def getWelcomeMsg(self):
        return self.ftp.getwelcome()
       
    def upload(self, filename):
        self.ftp.storbinary("STOR " + filename, file(filename, "rb"))
        
    def download(self, file):
        self.file = open(file, "wb")
        self.ftp.retrbinary('RETR' + file, self.ftp_file_printer_callback) 
        self.file.close()
        
    def ftp_file_printer_callback(self, data): self.file.write(data)
        
    def get_status(self): return self.status
       
    def listFiles(self, mimeInstance, showhidden = 0):
		mime = mimeInstance
		try:
			mylist, listdata = [], [("directory", mime.return_folder_mime(), ".." , "4096", "")]

			self.ftp.retrlines('LIST', mylist.append)
		except:
			return None
    
		for myitem in mylist:
			if showhidden == 0 and myitem[0] == ".": continue
			mystats = str(myitem).split()
			(txt_type, type, name, size, lastedit) = \
				(mystats[0][0] != '-' and "directory" or "file", 
				mystats[0][0] != '-' and mime.return_folder_mime() or mime.return_mime(myitem), 
				mystats[-1], 
				mystats[4], 
				str(mystats[5] + ' ' + mystats[6] + ' ' + mystats[7]))
			listdata.append((txt_type, type, name, size, lastedit))
			
		listdata.sort()
		return listdata

class Download(Thread):
	
        def __init__(self, filename, path, host, user, password):
            Thread.__init__(self)
            self.ftp = FTP()
            #self.file = file
            #self.path = path.get_text()
            #self.host = host.get_text()
            #self.user = user.get_text()
            #self.password = password.get_text()
            
            self.filename, self.path, self.host, self.user, self.password = \
            	filename, path, host, user, password

            self.received = 0
            
        def run(self):
            self.ftp.connect(self.host)
            self.ftp.login(self.user, self.password)
            self.ftp.cwd(self.path)
            self.size = self.ftp.size(self.file)
            self.handler = open(self.filename, "wb")
            self.ftp.retrbinary('RETR ' + self.filename, self.callback) 
            self.handler.close()
            self.ftp.quit()
        
        def callback(self, data):
            self.handler.write(data)
            self.received += len(data)
            print '%.3f%% \n' % (100*self.received/self.size) 

class Upload(Thread):
	
        def __init__(self, file, path, host, user, password):
            Thread.__init__(self)
            self.ftp = FTP()
            
            #self.filename = file
            #self.path = path.get_text()
            #self.host = host.get_text()
            #self.user = user.get_text()
            #self.password = password.get_text()
            
            self.filename, self.path, self.host, self.user, self.password = \
            	filename, path, host, user, password
            
        def run(self):
            self.ftp.connect(self.host)
            self.ftp.login(self.user, self.password)
            self.ftp.cwd(self.path)
            self.ftp.storbinary("STOR " + self.filename, file(self.filename, "rb"))
            print "Completato"
            self.ftp.quit()